import { create } from 'zustand';
import axiosInstance from '../api/axios';
import { endpoints } from '../api/endpoints';
import { getEmail,clearAuthData } from '../utils/storage';
import { default as initWasm, decrypt_reward_data } from './pkg/wasm_aes.js';

let wasmModule = null;
// 模块初始化，只执行一次
const loadWasmModule = async () => {
  if (wasmModule) return wasmModule; // 已加载
  try {
    // const { default: initWasm, decrypt_reward_data } = await import('../pkg/wasm_aes.js');
    await initWasm();
    wasmModule = { decrypt_reward_data };
  } catch (e) {
    console.warn("WASM 加载失败，使用 mock 解密逻辑");
    wasmModule = {
      decrypt_reward_data: (_email, _timestamp, encrypted_str) => {
        return atob(encrypted_str); // 简单 base64 解码模拟
      }
    };
  }
  return wasmModule;
};

const usePointsStore = create((set, get) => ({
  totalPoints: 0,
  sessionPoints: 0,
  rewards: [], // Array of { video_url, score }
  signature: null,
  security:null,
  timestamp: null,
  canEarnPoints: false,
  nextAvailability: '',
  isInitialized: false,
  isReporting: false,
  isTimerActive: false, // To control the timer in the UI

  // Action to check if the user can earn points today
  checkEligibility: async () => {
    try {
      const response = await axiosInstance.post(endpoints.CHECK_TODAY_INTEGRAL);
      const { flag, integral, next_availability } = response.data.data;
      set({
        canEarnPoints: flag,
        totalPoints: integral || 0,
        nextAvailability: next_availability,
        isInitialized: true,
      });
      // Start timer only if eligible
      if (flag) {
        set({ isTimerActive: true });
      }
    } catch (error) {
      console.error("Failed to check points eligibility:", error);
      set({ isInitialized: true, canEarnPoints: false });
    }
  },

  // Action to report earned points
  reportPoints: async () => {
    const { isReporting, rewards, security, timestamp } = get();
    const email = getEmail();
    // console.log("email:", isReporting,rewards,security,timestamp);

    // if (isReporting || rewards.length === 0 || !security || !timestamp || !email) return;
    
    set({ isReporting: true });

    try {
      const { decrypt_reward_data } = await loadWasmModule();
      const signture = decrypt_reward_data(email, timestamp, security);

      const totalScore = rewards.reduce((acc, reward) => acc + reward.score, 0);

    const response = await axiosInstance.post(endpoints.REPORT_SCORE, {
      all_score: totalScore,
      signture: signture,
    }).catch(error => { 
      // 刷新页面
      window.location.href = window.location.href.split('#')[0] + '?t=' + new Date().getTime();
      return;
    });
    

  

    const { add_score } = response.data.data;
    set((state) => ({
      totalPoints: state.totalPoints + add_score,
      sessionPoints: 0,
      rewards: [],
    }));
  } catch (error) {
    console.error("Failed to report points:", error);
  } finally {
    set({ isReporting: false });
  }
},

  // Accumulate points for a watched video segment
  accumulatePoints: (videoUrl) => {
    if (!get().canEarnPoints) return;
    const score = Math.floor(Math.random() * (30 - 11 + 1)) + 11;
    set((state) => ({
      sessionPoints: state.sessionPoints + score,
      rewards: [...state.rewards, { video_url: videoUrl, score }],
    }));
  },

  setSignature: (signature) => set({ signature }),
  setTotalPoints: (points) => set({ totalPoints: points }),
  setTimerActive: (isActive) => set({ isTimerActive: isActive }),
  setSecurity: (security) => set({ security }),
  setTimestamp: (timestamp) => set({ timestamp }), 

  // Reset state on component unmount
  reset: () => {
    set({
      sessionPoints: 0,
      rewards: [],
      signature: null,
      canEarnPoints: false,
      nextAvailability: '',
      isInitialized: false,
      isTimerActive: false,
    });
  },
}));

export default usePointsStore; 